﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncDemo
{
    class FrmAsync : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;

        public FrmAsync()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(75, 26);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(107, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "赋值运算";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(247, 26);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 28);
            this.textBox1.TabIndex = 1;
            // 
            // FrmAsync
            // 
            this.ClientSize = new System.Drawing.Size(532, 279);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "FrmAsync";
            this.Load += new System.EventHandler(this.FrmAsync_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void FrmAsync_Load(object sender, EventArgs e)
        {
           // System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Action<int> act = t=> { this.textBox1.Text = t.ToString(); };
            //创建一个线程去执行这个方法:创建的线程默认是前台线程
            Thread thread = new Thread(()=> {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(100);
                    this.textBox1.Invoke(act, i);
                    // this.textBox1.Invoke(t => { this.textBox1.Text = t.ToString(); }, i);这里不允许使用 lambda 表达式，因为里面传递的是一个委托类型，不是委托
                }
            });
            //Start方法标记这个线程就绪了，可以随时被执行，具体什么时候执行这个线程，由CPU决定
            //将线程设置为后台线程
            thread.IsBackground = true;
            thread.Start();
        }
    }
}
